
const babel = require('@babel/core')
const types = require('@babel/types')
const nodePath = require('path')



const logger = {
    visitor: {
        CallExpression(path, state) {
            const { node } = path
            if (types.isMemberExpression(node.callee)) {
                if (node.callee.object.name === 'console') {
                    if (['log', 'info', 'warn', 'error'].includes(node.callee.property.name)) {
                        const { line, column } = node.loc.start
                        const filename = state.file.opts.filename
                        const relativeName = nodePath.relative(__dirname, filename).replace(/\\/g, '/')
                        node.arguments.unshift(types.stringLiteral(`${relativeName}-${line}:${column}`))
                    }
                }
            }
        }
    }
}

const sourceCode = `
    const sum = function(a,b){
        console.log('日志')
        return a + b
    }
`

const result = babel.transform(sourceCode, {
    filename: 'sum.js',
    plugins: [logger]
})
console.log(result.code)